package com.boot.webflux.security.example2.handler;

import com.boot.webflux.security.example2.utils.RespUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 登录失败处理类
 */
@Component
@Slf4j
public class CloudAuthenticationFailureHandler  implements ServerAuthenticationFailureHandler {
    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException e) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (e instanceof UsernameNotFoundException) {
            log.info("【登录失败】" + e.getMessage());
            return RespUtil.writeMsg(response, 500, "用户名不存在");
        }
        if (e instanceof LockedException) {
            log.info("【登录失败】" + e.getMessage());
            return RespUtil.writeMsg(response, 500, "用户被冻结");
        }
        if (e instanceof BadCredentialsException) {
            log.info("【登录失败】" + e.getMessage());
            return RespUtil.writeMsg(response, 500, "用户名密码不正确");
        }
        return RespUtil.writeMsg(response, 500, "登录失败");
    }
}
